using System;
using BlogEngine.Core;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using BlogEngine.Core.Web.Controls;

/// <summary>
/// Add flv video player(s) to the post
/// </summary>
[Extension("flv flash video player", "1.0.0.0", "betaparticle.com")]
public class flvplayer
{
    private const string _audioroot = "flv/";
    private const string _jsfile = "";
    private static long _cnt = 0;

    public flvplayer()
    {
        Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving);
    }

    /// <summary>
    /// An event that handles ServingEventArgs
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Post_Serving(object sender, ServingEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.Body))
        {
            // only process the posts
            if (e.Location == ServingLocation.PostList || e.Location == ServingLocation.SinglePost)
            {
                string regex = @"\[flv:.*?\.flv]";
                MatchCollection matches = Regex.Matches(e.Body, regex);

                if (matches.Count > 0)
                {
                    //AddJsToTheHeader();

                    string filename = string.Empty;
                    string filepath = string.Empty;
                    string player = string.Empty;

                    foreach (Match match in matches)
                    {
                        filename = match.Value.Replace("[flv:", "").Replace("]", "").Trim();
                        player = PlayerObject(filename);
                        //player = "<script type=\"text/javascript\">InsertPlayer(\"" + player + "\");</script>";
                        e.Body = e.Body.Replace(match.Value, player);
                    }
                }
            }
        }
    }

    /// <summary>
    /// Inject JavaScript file into the header of the post
    /// </summary>
    private void AddJsToTheHeader()
    {
        // get a page handler
        System.Web.UI.Page pg = (System.Web.UI.Page)HttpContext.Current.CurrentHandler;
        bool added = false;

        // check if script already added to the page header
        foreach (Control ctl in pg.Header.Controls)
        {
            if (ctl.GetType() == typeof(HtmlGenericControl))
            {
                HtmlGenericControl gc = (HtmlGenericControl)ctl;
		if (gc.Attributes["src"] != null)
		{
   		    if (gc.Attributes["src"].Contains(_jsfile))
		    {
       		        added = true;
                    }
		}
            }
        }

        if (!added)
        {
            HtmlGenericControl js = new HtmlGenericControl("script");
            js.Attributes.Add("type", "text/javascript");
            js.Attributes.Add("src", AudioRoot() + _jsfile);

            pg.Header.Controls.Add(js);
        }
    }

    /// <summary>
    /// Build object tag
    /// </summary>
    /// <param name="soundFile">Name of the mp3 file ("my song.mp3")</param>
    /// <returns>Flash object markup</returns>
    private string PlayerObject(string soundFile)
    {
        string sFile = string.Empty;
        string[] sFiles = soundFile.Split(",".ToCharArray());

        foreach (string file in sFiles)
        {
            if (file.Substring(0, 7) == "http://")
            {
                sFile += file;
            }
            else
            {
                sFile += AudioRoot() + file;
            }
            sFile += ",";
        }

        sFile = sFile.Substring(0, sFile.Length - 1);
        sFile = HttpUtility.UrlEncode(sFile);

        string s = "<p>"
        + "<object type='application/x-shockwave-flash' height='240' width='320' data='{0}flvplayer.swf?file={2}&autostart=false' wmode='transparent'>"
        + "<param value='{0}flvplayer.swf?file={2}&autostart=false' name='movie' />"
        + "<param value='transparent' name='wmode' />"
        + "</object>"
        + "</p>";

        _cnt++;

        return String.Format(s, AudioRoot(), _cnt, sFile);
    }

    /// <summary>
    /// Virtual path to audio folder
    /// </summary>
    /// <returns>Path to the audio folder</returns>
    private string AudioRoot()
    {
        string VirtualPath = HttpContext.Current.Request.Path;
        string audioRoot = VirtualPath.Substring(0, VirtualPath.LastIndexOf("/") + 1) + _audioroot;
        return audioRoot;
    }
}
